package com.dis.service.service.impl;

import com.dis.common.constant.MessageConstant;
import com.dis.common.constant.StatusConstant;
import com.dis.pojo.dto.PolicyDTO;
import com.dis.pojo.entity.Policy;
import com.dis.common.exception.BaseException;
import com.dis.service.mapper.PolicyMapper;
import com.dis.pojo.queryDTO.PolicyPageQueryDTO;
import com.dis.common.result.PageResult;
import com.dis.service.service.PolicyService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
@Slf4j
public class PolicyServiceImpl implements PolicyService {

    @Autowired
    private PolicyMapper policyMapper;

    @Override
    public void save(PolicyDTO policyDTO) {
        Policy policy = new Policy();
        BeanUtils.copyProperties(policyDTO, policy);

        // 检查策略名称是否已存在
        Policy existingPolicy = policyMapper.getByPolicyName(policy.getPolicyName());
        if (existingPolicy != null) {
            throw new BaseException(MessageConstant.POLICY_NAME_EXISTS);
        }

        policy.setStatus(StatusConstant.ENABLE);
        policy.setCreateTime(LocalDateTime.now());
        policy.setUpdateTime(LocalDateTime.now());

        policyMapper.insert(policy);
    }

    @Override
    public PageResult pageQuery(PolicyPageQueryDTO policyPageQueryDTO) {
        PageHelper.startPage(policyPageQueryDTO.getPage(), policyPageQueryDTO.getPageSize());

        Page<Policy> page = policyMapper.pageQuery(policyPageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    public void startOrStop(Integer status, Long id) {
        Policy policy = Policy.builder()
                .policyId(id)
                .status(status)
                .updateTime(LocalDateTime.now())
                .build();

        policyMapper.update(policy);
    }

    @Override
    public void deleteById(Long id) {
        policyMapper.deleteById(id);
    }

    @Override
    public void update(PolicyDTO policyDTO) {
        Policy policy = new Policy();
        BeanUtils.copyProperties(policyDTO, policy);
        policy.setUpdateTime(LocalDateTime.now());

        policyMapper.update(policy);
    }
}
